import { Container } from '@/react-dom/hostConfig';
import { ReactElementType } from '@/shared/ReactTypes';
import { FiberNode, FiberRootNode } from './fiber';
import { requestUpdateLane } from './fiberLanes';
import {
	createUpdate,
	createUpdateQueue,
	enqueueUpdate,
	UpdateQueue
} from './updateQueue';
import { scheduleUpdateOnFiber } from './workLoop';
import { HostRoot } from './workTags';

export function createContainer(container: Container) {
	// 创建hostRootFiber对象
	const hostRootFiber = new FiberNode(HostRoot, {}, null);
	// FiberRootNode  fiber根节点(用来管理整个fiber树) 与 hostRootFiber 产生关联
	const root = new FiberRootNode(container, hostRootFiber);
	// 初始化update任务对象
	hostRootFiber.updateQueue = createUpdateQueue();
	// FiberRootNode fiber根节点
	return root;
}

export function updateContainer(
	element: ReactElementType | null,
	root: FiberRootNode
) {
	const hostRootFiber = root.current;
	// 渲染优先级
	const lane = requestUpdateLane();
	// update对象的action属性 =>  根组件(App)
	const update = createUpdate<ReactElementType | null>(element, lane);
	// 把上面生成的update对象关联到hostRootFiber.updateQueue.shared.pending
	enqueueUpdate(
		hostRootFiber.updateQueue as UpdateQueue<ReactElementType | null>,
		update
	);

	scheduleUpdateOnFiber(hostRootFiber, lane);
	return element;
}
